<template>
  <div class="borrowing-records-container">
    <div class="page-header">
      <h1>我的借阅记录</h1>
      <p>管理您的图书借阅历史</p>
    </div>

    <!-- 筛选器 -->
    <div class="filters">
      <el-card>
        <el-form :model="filters" :inline="true">
          <el-form-item label="状态">
            <el-select v-model="filters.status" placeholder="全部状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="借阅中" value="BORROWED" />
              <el-option label="已归还" value="RETURNED" />
              <el-option label="已逾期" value="OVERDUE" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filters.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadRecords(true)">查询</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 统计信息 -->
    <div class="statistics">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="8">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.totalBorrowed }}</div>
            <div class="stat-label">累计借阅</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="8">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.currentBorrowed }}</div>
            <div class="stat-label">当前借阅</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="8">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.overdue }}</div>
            <div class="stat-label">逾期未还</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 借阅记录列表 -->
    <div class="records-list">
      <el-card>
        <div v-loading="loading">
          <div 
            v-for="record in records"
            :key="record.id"
            class="record-item"
          >
            <div class="record-book">
              <el-image
                :src="record.book.coverImage || '/default-book.jpg'"
                fit="cover"
                class="book-cover"
              />
              <div class="book-info">
                <h3 class="book-title" @click="goToBookDetail(record.book.id)">
                  {{ record.book.title }}
                </h3>
                <p class="book-author">{{ record.book.author }}</p>
                <p class="book-publisher">{{ record.book.publisher }}</p>
              </div>
            </div>
            
            <div class="record-details">
              <div class="detail-item">
                <span class="label">借阅时间：</span>
                <span class="value">{{ formatTime(record.borrowTime) }}</span>
              </div>
              <div class="detail-item">
                <span class="label">应还时间：</span>
                <span class="value" :class="{ 'overdue': isOverdue(record) }">
                  {{ formatTime(record.dueTime) }}
                </span>
              </div>
              <div class="detail-item" v-if="record.returnTime">
                <span class="label">归还时间：</span>
                <span class="value">{{ formatTime(record.returnTime) }}</span>
              </div>
              <div class="detail-item" v-if="record.renewCount > 0">
                <span class="label">续借次数：</span>
                <span class="value">{{ record.renewCount }}次</span>
              </div>
            </div>
            
            <div class="record-status">
              <el-tag 
                :type="getStatusType(record.status)"
                size="large"
              >
                {{ getStatusText(record.status) }}
              </el-tag>
              
              <div class="record-actions">
                <el-button 
                  v-if="record.status === 'BORROWED' && !isOverdue(record)"
                  type="primary" 
                  size="small"
                  @click="renewBook(record)"
                  :disabled="record.renewCount >= 3"
                >
                  续借
                </el-button>
                <el-button 
                  v-if="record.status === 'BORROWED'"
                  type="success" 
                  size="small"
                  @click="returnBook(record)"
                >
                  归还
                </el-button>
                <el-button 
                  type="default" 
                  size="small"
                  @click="goToBookDetail(record.book.id)"
                >
                  查看图书
                </el-button>
              </div>
            </div>
          </div>
          
          <div v-if="records.length === 0 && !loading" class="no-records">
            <el-empty description="暂无借阅记录" />
          </div>
        </div>
        
        <!-- 分页 -->
        <div class="pagination" v-if="total > 0">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="loadRecords(true)"
            @current-change="loadRecords(false)"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getMyBorrowingRecords,
  getBorrowingStatistics,
  renewBook as apiRenewBook,
  returnBook as apiReturnBook
} from '@/api/library'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const records = ref([])
const statistics = ref({
  totalBorrowed: 0,
  currentBorrowed: 0,
  overdue: 0
})
const total = ref(0)

// 筛选器
const filters = reactive({
  status: '',
  dateRange: null
})

// 分页参数
const pagination = reactive({
  page: 1,
  size: 10
})

// 获取借阅记录
const loadRecords = async (reset = false) => {
  if (reset) {
    pagination.page = 1
  }
  
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      status: filters.status,
      startDate: filters.dateRange?.[0],
      endDate: filters.dateRange?.[1]
    }
    
    const response = await getMyBorrowingRecords(params)
    if (response.code === 200) {
      records.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error('获取借阅记录失败')
    }
  } catch (error) {
    console.error('获取借阅记录失败:', error)
    ElMessage.error('获取借阅记录失败')
  } finally {
    loading.value = false
  }
}

// 获取统计信息
const loadStatistics = async () => {
  try {
    const response = await getBorrowingStatistics()
    if (response.code === 200) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 续借图书
const renewBook = async (record) => {
  try {
    await ElMessageBox.confirm(`确认要续借《${record.book.title}》吗？`, '确认续借', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await apiRenewBook(record.id)
    ElMessage.success('续借成功')
    loadRecords(false)
    loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('续借失败:', error)
      ElMessage.error('续借失败')
    }
  }
}

// 归还图书
const returnBook = async (record) => {
  try {
    await ElMessageBox.confirm(`确认要归还《${record.book.title}》吗？`, '确认归还', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await apiReturnBook(record.id)
    ElMessage.success('归还成功')
    loadRecords(false)
    loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('归还失败:', error)
      ElMessage.error('归还失败')
    }
  }
}

// 跳转到图书详情
const goToBookDetail = (bookId) => {
  router.push(`/library/book/${bookId}`)
}

// 重置筛选器
const resetFilters = () => {
  filters.status = ''
  filters.dateRange = null
  loadRecords(true)
}

// 工具函数
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleDateString()
}

const isOverdue = (record) => {
  if (record.status !== 'BORROWED') return false
  return new Date() > new Date(record.dueTime)
}

const getStatusType = (status) => {
  const typeMap = {
    'BORROWED': 'warning',
    'RETURNED': 'success',
    'OVERDUE': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'BORROWED': '借阅中',
    'RETURNED': '已归还',
    'OVERDUE': '已逾期'
  }
  return textMap[status] || status
}

// 页面加载
onMounted(() => {
  loadRecords(true)
  loadStatistics()
})
</script>

<style lang="scss" scoped>
.borrowing-records-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  
  h1 {
    font-size: 32px;
    color: #303133;
    margin: 0 0 10px 0;
  }
  
  p {
    color: #606266;
    font-size: 16px;
    margin: 0;
  }
}

.filters {
  margin-bottom: 20px;
}

.statistics {
  margin-bottom: 20px;
  
  .stat-card {
    background: white;
    padding: 20px;
    border-radius: 8px;
    text-align: center;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    
    .stat-number {
      font-size: 32px;
      font-weight: bold;
      color: #409eff;
      margin-bottom: 8px;
    }
    
    .stat-label {
      color: #606266;
      font-size: 14px;
    }
  }
}

.records-list {
  .record-item {
    display: flex;
    gap: 20px;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .record-book {
      display: flex;
      gap: 12px;
      flex-shrink: 0;
      
      .book-cover {
        width: 60px;
        height: 80px;
        border-radius: 4px;
      }
      
      .book-info {
        .book-title {
          margin: 0 0 8px 0;
          font-size: 16px;
          font-weight: 500;
          cursor: pointer;
          color: #409eff;
          
          &:hover {
            text-decoration: underline;
          }
        }
        
        .book-author,
        .book-publisher {
          margin: 4px 0;
          color: #606266;
          font-size: 14px;
        }
      }
    }
    
    .record-details {
      flex: 1;
      
      .detail-item {
        margin: 8px 0;
        
        .label {
          color: #909399;
          font-size: 14px;
        }
        
        .value {
          color: #303133;
          font-size: 14px;
          
          &.overdue {
            color: #f56c6c;
            font-weight: bold;
          }
        }
      }
    }
    
    .record-status {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      gap: 12px;
      
      .record-actions {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
      }
    }
  }
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

@media (max-width: 768px) {
  .borrowing-records-container {
    padding: 10px;
  }
  
  .statistics {
    .el-row {
      gap: 10px;
    }
  }
  
  .record-item {
    flex-direction: column;
    gap: 15px;
    
    .record-status {
      align-items: flex-start;
      flex-direction: row;
      justify-content: space-between;
    }
  }
}
</style>
